import { Injectable } from '@angular/core';

import { Http } from '@angular/http';
import { Service } from '../../server/server';

@Injectable()
export class UserRightService {

    private baseUrl: string = '';
    private createUserId:any;

    constructor(private http: Http, private server: Service) {
        this.baseUrl = server.zsurl;
        this.createUserId = this.server.getuser();
    }

    getRights(userName: string): Promise<Array<any>> {
        let url = this.server.baseUrl + 'admin/pusers/getMenuAllByUserName?userName=' + encodeURIComponent(userName);
        return this.http
            .get(url)
            .toPromise()
            .then(res => {
                let r = res.json();
                if (r.result_code !== '0000') {
                    throw new Error(r.message);
                } else {
                    return this.processRights(r.result);
                }
            });
    }
    //修改后
    refreshright(){
        let url = this.server.baseUrl + 'admin/pusers/resetMenu';
        let data = {userId:this.createUserId}
        return this.http
        .post(url,data)
        .toPromise()
        .then(res => {
            let r = res.json();
            //console.log(r)
            if (r.result_code !== '0000') {
                throw new Error(r.message);
            } else {
                //console.log(this.processRights(r.result))
                return this.processRights(r.result);
            }
        });
      }

    private processRights(list: Array<any>): any {
        let result: any = {};
        for (let item of list) {
            let code: string = item.menuCode;
            let ps: string = item.permissonCode;
            result[code] = {};
            result[code]['permissions'] = ps;
            let arr: Array<string> = ps.split(/\,/g);
            for (let p of arr) {
                if (p) {
                    result[code][p] = true;
                }
            }
        }
        return result;
    }

}